package com.quick.generator.controller;


import com.quick.common.annotation.Log;
import com.quick.common.core.controller.BaseController;
import com.quick.common.core.domain.ApiResponse;
import com.quick.common.core.text.Convert;
import com.quick.common.enums.BusinessTypeEnum;
import com.quick.generator.domain.GenTable;
import com.quick.generator.domain.GenTableColumn;
import com.quick.generator.service.GenTableColumnService;
import com.quick.generator.service.GenTableService;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 代码生成 操作处理
 *
 * @Author: quick
 */
@RestController
@RequestMapping("/tool/gen")
public class GenController extends BaseController {
    @Autowired
    private GenTableService genTableService;

    @Autowired
    private GenTableColumnService genTableColumnService;

    /**
     * 查询代码生成列表
     */
    @ApiOperation(value = "查询代码生成列表")
    @GetMapping("/list")
    public ApiResponse genList(GenTable genTable) {
        try {
            startPage();
            List<GenTable> list = genTableService.selectGenTableList(genTable);
            return paging(list);
        } finally {
            clearPage();
        }

    }

    /**
     * 修改代码生成业务
     */
    @ApiOperation(value = "修改代码生成业务")
    @GetMapping(value = "/{tableId}")
    public ApiResponse getInfo(@PathVariable Long tableId) {
        GenTable table = genTableService.selectGenTableById(tableId);
        List<GenTable> tables = genTableService.selectGenTableAll();
        List<GenTableColumn> list = genTableColumnService.selectGenTableColumnListByTableId(tableId);
        Map<String, Object> map = new HashMap<>(3);
        map.put("info", table);
        map.put("rows", list);
        map.put("tables", tables);
        return success(map);
    }

    /**
     * 查询数据库列表
     */
    @ApiOperation(value = "查询数据库列表")
    @GetMapping("/db/list")
    public ApiResponse dataList(GenTable genTable) {
        try {
            startPage();
            List<GenTable> list = genTableService.selectDbTableList(genTable);
            return paging(list);
        } finally {
            clearPage();
        }
    }

    /**
     * 查询数据表字段列表
     */
    @ApiOperation(value = "查询数据表字段列表")
    @GetMapping(value = "/column/{tableId}")
    public ApiResponse columnList(@PathVariable Long tableId) {
        List<GenTableColumn> list = genTableColumnService.selectGenTableColumnListByTableId(tableId);
        return total(list);
    }

    /**
     * 导入表结构（保存）
     */
    @ApiOperation(value = "导入表结构")
    @Log(title = "代码生成", businessType = BusinessTypeEnum.IMPORT)
    @PostMapping("/importTable")
    public ApiResponse importTableSave(String tables) {
        String[] tableNames = Convert.toStrArray(tables);
        // 查询表信息
        List<GenTable> tableList = genTableService.selectDbTableListByNames(tableNames);
        genTableService.importGenTable(tableList);
        return success();
    }

    /**
     * 修改保存代码生成业务
     */
    @ApiOperation(value = "修改保存代码生成业务")
    @Log(title = "代码生成", businessType = BusinessTypeEnum.UPDATE)
    @PutMapping
    public ApiResponse editSave(@Validated @RequestBody GenTable genTable) {
        genTableService.validateEdit(genTable);
        genTableService.updateGenTable(genTable);
        return success();
    }

    /**
     * 删除代码生成
     */
    @ApiOperation(value = "删除代码生成")
    @Log(title = "代码生成", businessType = BusinessTypeEnum.DELETE)
    @DeleteMapping("/{tableIds}")
    public ApiResponse remove(@PathVariable Long[] tableIds) {
        genTableService.deleteGenTableByIds(tableIds);
        return success();
    }
    /**
     * 生成测试数据
     */
    @ApiOperation(value = "生成测试数据")
    @GetMapping("/testData/{tableId}")
    public ApiResponse testData(@PathVariable("tableId") Long tableId) throws IOException {
        genTableService.testData(tableId);
        return success();
    }
    /**
     * 预览代码
     */
    @ApiOperation(value = "预览代码")
    @GetMapping("/preview/{tableId}")
    public ApiResponse preview(@PathVariable("tableId") Long tableId) throws IOException {
        Map<String, String> dataMap = genTableService.previewCode(tableId);
        return success(dataMap);
    }

    /**
     * 生成代码（下载方式）
     */
    @ApiOperation(value = "生成代码-下载方式")
    @Log(title = "代码生成", businessType = BusinessTypeEnum.GEN_CODE)
    @GetMapping("/download/{tableName}")
    public void download(HttpServletResponse response, @PathVariable("tableName") String tableName) throws IOException {
        byte[] data = genTableService.downloadCode(tableName);
        genCode(response, data);
    }

    /**
     * 生成代码（自定义路径）
     */
    @ApiOperation(value = "生成代码-自定义路径")
    @Log(title = "代码生成", businessType = BusinessTypeEnum.GEN_CODE)
    @GetMapping("/genCode/{tableName}")
    public ApiResponse genCode(@PathVariable String tableName) {
        genTableService.generatorCode(tableName);
        return success();
    }

    /**
     * 同步数据库
     */
    @ApiOperation(value = "同步数据库")
    @Log(title = "代码生成", businessType = BusinessTypeEnum.UPDATE)
    @GetMapping("/syncDb/{tableName}")
    public ApiResponse syncDb(@PathVariable String tableName) {
        genTableService.syncDb(tableName);
        return success();
    }

    /**
     * 批量生成代码
     */
    @ApiOperation(value = "批量生成代码")
    @Log(title = "代码生成", businessType = BusinessTypeEnum.GEN_CODE)
    @GetMapping("/batchGenCode")
    public void batchGenCode(HttpServletResponse response, String tables) throws IOException {
        String[] tableNames = Convert.toStrArray(tables);
        byte[] data = genTableService.downloadCode(tableNames);
        genCode(response, data);
    }

    /**
     * 生成zip文件
     */
    private void genCode(HttpServletResponse response, byte[] data) throws IOException {
        response.reset();
        response.addHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
        response.addHeader(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, "Content-Disposition");
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"quick.zip\"");
        response.addHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(data.length));
        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
        IOUtils.write(data, response.getOutputStream());

    }
}